<?php
// +----------------------------------------------------------------------
// | title: 标题注释
// +----------------------------------------------------------------------
// | Author: TZ.Leong
// +----------------------------------------------------------------------
// | Date: 2019/7/3 10:31
// +----------------------------------------------------------------------

namespace app\single\controller;

use app\admin\model\ApiOperateModel;
use app\single\model\{
    BanModel,
    DayOnlineModel,
    LogBanModel,
    MailModel,
    RoleMailModel,
    RoleModel,
// VarModel
};
use cmf\controller\AdminBaseController;
use cmf\lib\{Http, Sign};
use think\{
    Db,
    db\exception\DataNotFoundException,
    db\exception\DbException,
    db\exception\ModelNotFoundException,
    db\Query,
    db\Where,
    facade\Cache,
    facade\Log
};

class PlayerManageController extends AdminBaseController
{
    protected $roleModel;

    public function initialize()
    {
        parent::initialize();
        $this->roleModel = new RoleModel();
    }

    /**
     * 玩家列表
     * @return mixed
     */
    public function playerLists()
    {
        $sort = $this->request->param("sortBy", "");
        try {

            $data = $this->roleModel->alias("r")
                ->where(function (Query $query) {
                    if ($nickname = $this->request->param("nickname", "", "trim")) {
                        $query->where("name LIKE '%$nickname%' OR id = '$nickname'");
                    }
                    if ($accname = $this->request->param("accname", "", "trim")) {
                        $query->where("account", "like", "%$accname%");
                    }
                    $onlineFlag = $this->request->param("online_flag", -1, "intval");
                    if ($onlineFlag != -1) {
                        $query->where("is_online", $onlineFlag);
                    }
                    $minLev = $this->request->param("min_lev", 0, "intval");
                    $maxLev = $this->request->param("max_lev", 999, "intval");
                    $query->whereBetween("lev", [$minLev, $maxLev]);

                    $sDay = $this->request->param("sDay", "", "date");
                    $eDay = $this->request->param("eDay", "", "date");
                    if (!empty($sDay) && !empty($eDay)) {
                        $query->whereBetween("reg_time", [strtotime($sDay . " 00:00:00"), strtotime($eDay . " 23:59:59")]);
                    }
                    $loginIp = $this->request->param("login_ip", "", "trim");
                    if ($loginIp) {
                        $query->where("last_login_ip", $loginIp);
                    }
                })
                //            ->leftJoin([config("database.game").".role_economy" => "pe"],"r.id = pe.role_id")
                ->leftJoin(["role_pay_total" => "rpt"], "rpt.role_id = r.id")
                ->field("r.*,rpt.rmb")
                ->order($this->getOrderBy($sort))
                ->paginate($this->request->param("pagesize", 20));

            Log::write("debug player list search sql  " . $this->roleModel->getLastSql());
            $data->appends($this->request->param());
            $this->assign("data", $data);
            $this->assign("page", $data->render());
        } catch (\Exception $e) {
            $data = [];
            $this->assign("data", $data);
            $this->assign("page", null);
        }
        return $this->fetch();
    }


    public function setwhiteip()
    {
        if ($this->request->isPost()) {
            $ip = $this->request->param("ip");
            $key = PLATFORM . PLAT_SERVER_ID . "white_ip_list";
            $ipParts = explode('.', $ip);
            $cachedata = cache($key);
            if($cachedata){
                $iplist =json_decode($cachedata);
            }else {
                $iplist=[];
            }

            $res = PHP2Erlang(BACKGROUND_RELEASE_IP, [implode(',', $ipParts)]);
            if ($res  && $res["code"] ==0) {
                if (!in_array($ip, $iplist)) {
                    $iplist[] = $ip;
                }
                
                cache($key, json_encode($iplist), strtotime(date('Y-m-d 23:59:59')) - time());
                $this->success("设置成功");
            } else {
                $this->error("设置失败");
            }

        } else {
            $key = PLATFORM . PLAT_SERVER_ID . "white_ip_list";
            $cachedata = cache($key);
            if ($cachedata) {
                $iplist = json_decode($cachedata, true);
            } else {
                $iplist = [];
            }
            $this->assign("ip", $this->request->ip(0, true, false));
            $this->assign("data", $iplist);
            return $this->fetch();
        }
    }

    /**
     * 获取排序规则
     */
    private function getOrderBy($sort): string
    {
        switch ($sort) {
            case 1:
                $strings = "r.lev ASC";
                break;
            case 2:
                $strings = "r.lev DESC";
                break;
            case 3:
                $strings = "r.fc ASC";
                break;
            case 4:
                $strings = "r.fc DESC";
                break;
            case 5:
                $strings = "r.cur_id DESC";
                break;
            case -1:
            default:
                $strings = "r.reg_time DESC";
                break;
        }
        return $strings;
    }


    private function updatePlayer($vo)
    {
        $cache = Cache::store("file");
        $serverInfo = $cache->get("server_info");
        $params = [
            "platform" => $vo["pf"],
            "server_id" => $vo["zone_id"],
            "username" => $vo["account"],
            "player_id" => $vo["id"],
            "name" => $vo["name"],
            "sex" => $vo["sex"],
            "gold" => $vo["gold"],
            "level" => $vo["lev"],
            "power" => $vo["fc"],
            "login_time" => $vo["last_login_time"],
            "reg_time" => $vo["reg_time"],
            "login_ip" => $vo["last_login_ip"],
            "status" => $vo["state"],
            "time" => time(),
            "hook_id" => $vo["cur_id"] ?? 1,
        ];
        Log::write("DEBUG UPDATE PLAYER INFO" . json_encode($params, true));
        $params["sign"] = Sign::buildMD5sign($params, config("secure." . GAME_NAME . '_key.CLIENT'));
        try {
            $url = $serverInfo["api_url"] . "/client/update_player";
            $result = Http::post($url, $params);
            Log::write("update_player success,params:=>" . json_encode($params) . "result=>" . json_encode($result, true) . "api_url" . $url);
        } catch (\Exception $e) {
            Log::write("update_player error: " . $e->getMessage());
        }
    }

    /**
     * 禁言 / 解禁言
     */
    public function forbidTalk()
    {
        $playerId = $this->request->param('role_id', 0);
        $operateType = $this->request->param('oper_type', '', "trim");
        if (empty($operateType) || $playerId <= 0) {
            $this->error("参数不正确");
        }
        //查询玩家当前禁言状态
        $info = $this->roleModel->find($playerId);
        $BanModel = new LogBanModel();

        //开始操作禁言
        if ($operateType == "forbid") {
            $ban_type = $this->request->param('type', '0', "intval");

            //是否已经被禁言了
            if ($info["talk_lim_time"] > time()) {
                $this->error('该玩家已经被禁言');
            }
            //通知禁言
            $shutUpResult = PHP2Erlang(BACKGROUND_ACHAT_BAN, [$playerId, $ban_type]);
            $bantime = time();
            switch ($ban_type) {
                case 0:
                    $bantime += 5 * 60; //5分钟
                    break;
                case 1:
                    $bantime += 10 * 60; //10分钟
                    break;
                case 2:
                    $bantime += 30 * 60; //30分钟
                    break;
                case 3:
                    $bantime += 60 * 60; //60分钟
                    break;
                case 4:
                    $bantime += 2 * 60 * 60; //2小时
                    break;
                case 5:
                    $bantime += 6 * 60 * 60; //6小时
                    break;
                case 6:
                    $bantime += 24 * 60 * 60; //24小时
                    break;
                case 7:
                    $bantime += 24 * 3 * 60 * 60; //3天
                    break;
                case 8:
                    $bantime += 24 * 7 * 60 * 60; //7天
                    break;
                case 9:
                    $bantime += 365 * 60 * 60; //1年
                    break;

            }
            if ($shutUpResult["code"] === 0) {
                $info["status"] = 1; //设置玩家状态为1 禁止状态
                $this->roleModel->where(array("id" => $playerId))->update(array("talk_lim_time" => $bantime));
                $this->updatePlayer($info);
                $BanModel->create([
                    "player_id" => $playerId,
                    "ban_type" => 1,
                    "end_time" => $bantime,
                    "reason" => "后台封禁",
                    "operator" => session("__USERNAME__")
                ]);
                $this->success('已禁言当前玩家');
            } else {
                $this->error($shutUpResult["data"]);
            }
        } else {
            //free 解禁言操作
            if ($info["talk_lim_time"] < time()) {
                $this->error('该玩家没有被禁言');
            }
            //通知解除禁言
            $shutUpResult = PHP2Erlang(BACKGROUND_ACHAT_BAN, [$playerId, 100]);
            Log::write("debug shutdown: " . json_encode($shutUpResult));
            if ($shutUpResult["code"] === 0) {
                $info["status"] = 0; //设置玩家状态为0
                $BanModel->create([
                    "player_id" => $playerId,
                    "ban_type" => 2,
                    "end_time" => null,
                    "reason" => "后台解封",
                    "operator" => session("__USERNAME__")
                ]);

                $this->roleModel->where(array("id" => $playerId))->update(array("talk_lim_time" => 0));
                $this->updatePlayer($info);
                $this->success('已解除当前玩家禁言状态');
            } else {
                $this->error($shutUpResult["data"]);
            }
        }
    }

    /**
     * 封号 / 解除封号
     */
    public function forbidUser()
    {
        $roleId = $this->request->param('role_id', 0);
        $operateType = $this->request->param('oper_type', '', "trim");
        if (empty($operateType) || $roleId <= 0) {
            $this->error("参数不正确");
        }
        $apiModel = new ApiOperateModel();
        $BanModel = new LogBanModel();
        //查询玩家当前账号状态
        $info = $this->roleModel->find($roleId);
        $state = (int) $info["state"];
        //开始操作禁言
        if ($operateType == "lock") {
            //封号原因
            $reason = $this->request->param("reason", "", "trim");
            if (empty($reason)) {
                $this->error('请填写封号原因!!!');
            }
            //是否已经被封号了
            if ($state == 1) {
                $this->error('该玩家已经是封号状态');
            }
            //通知封号
            $shutUpResult = PHP2Erlang(BACKGROUND_ALOGIN_BAN, [$roleId, 1]);
            if ($shutUpResult["code"] === 0) {
                //封号成功，写封号日志
                $apiModel->addApiLog(1, json_encode(array("reason" => $reason)), $roleId);
                $info["status"] = 1; //设置玩家状态为1 禁止状态

                $BanModel->create([
                    "player_id" => $roleId,
                    "ban_type" => 3,
                    "end_time" => null,
                    "reason" => $reason,
                    "operator" => session("__USERNAME__")
                ]);

                $this->roleModel->where(array("id" => $roleId))->update(array("state" => 1));
                $this->updatePlayer($info);
                $this->success('操作封号成功');
            } else {
                $this->error($shutUpResult["data"]);
            }
        } else {
            //free 解禁言操作
            if ($state == 0) {
                $this->error('该账号未被封号');
            }
            //通知解除禁言
            try {
                $shutUpResult = PHP2Erlang(BACKGROUND_ALOGIN_BAN, [$roleId, 0]);
            } catch (\Exception $e) {

            }
            if ($shutUpResult["code"] === 0) {
                //解除封号成功，写解除日志
                $BanModel->create([
                    "player_id" => $roleId,
                    "ban_type" => 4,
                    "end_time" => null,
                    "reason" => "后台解封",
                    "operator" => session("__USERNAME__")
                ]);
                $apiModel->addApiLog(1, json_encode(array("reason" => "解除封号")), $roleId);
                $info["status"] = 0; //设置玩家状态为1 禁止状态
                $this->roleModel->where(array("id" => $roleId))->update(array("state" => 0));
                $this->updatePlayer($info);
                $this->success('操作解除封号成功');
            } else {
                $this->error($shutUpResult["data"]);
            }
        }
    }

    /**
     * 封禁IP
     */
    public function forbidIp()
    {
        $ip = $this->request->param('role_id', "", "trim");
        $operateType = $this->request->param('oper_type', '', "trim");
        if (empty($operateType) || empty($ip)) {
            $this->error("参数不正确");
        }
        if (!filter_var($ip, FILTER_VALIDATE_IP)) {
            $this->error("IP格式不正确");
        }
        $type = 1;
        $banModel = new BanModel();
        $apiModel = new ApiOperateModel();
        //此ip是否已经被封
        $checkRes = $banModel->checkValue($type, $ip);
        if ($operateType == "lock_ip") {
            $reason = $this->request->param("reason", "", "trim");
            if (empty($reason)) {
                $this->error('请填写封此IP的原因!');
            }
            if ($checkRes) {
                $this->error("此IP已经是被封状态!");
            }
            if (false !== $banModel->addValue($type, $ip)) {
                $resArr = PHP2Erlang(BACKGROUND_IP_BAN, [1, '"' . $ip . '"']);
                if ($resArr["code"] === 0) {
                    $apiModel->addApiLog(3, json_encode(array("reason" => $reason)), $ip);
                    $this->success('IP封锁成功');
                } else {
                    $this->error($resArr["data"]);
                }
            } else {
                $this->error("封锁IP入库失败!");
            }
        } else {
            if (!$checkRes) {
                $this->error("此IP没有处于被封状态!");
            }
            if (false !== $banModel->deleteValue($type, $ip)) {
                $resArr = PHP2Erlang(BACKGROUND_IP_BAN, [0, '"' . $ip . '"']);
                if ($resArr["code"] === 0) {
                    $apiModel->addApiLog(3, json_encode(array("reason" => "解除IP封锁")), $ip);
                    $this->success('解除IP封锁成功!');
                } else {
                    $this->error($resArr["data"]);
                }
            }
            $this->error("解除IP封锁删除数据失败!");
        }
    }

    /**
     * 玩家详细信息页
     */
    public function playerInfo()
    {
        //玩家ID
        $roleId = $this->request->param('role_id', 0);
        if (empty($roleId)) {
            $this->error('玩家ID为空');
        }
        //游戏库
        $gameDb = config("database.game");
        //玩家信息表
        $userInfo = $this->roleModel->find($roleId);
        Log::write("debug userinfo: " . json_encode($userInfo));
        if ($userInfo) {
            $userInfo = $userInfo->toArray();
            //            Log::write("debug userinfo: " . json_encode($userInfo));
            //玩家资产
//            $userInfo += (array)Db::table($gameDb . ".role_assets")->find($roleId);
            //充值数据
            $userInfo += (array) Db::table("role_pay_total")->find($roleId);

            $loginfo = (array) Db::table(config("database.game") . ".role_login")->find($roleId);
            //vip等级
//            $userInfo += (array)Db::table($gameDb . ".role_vip")->field("level As vip_lv")->find($roleId);


            $userArr = explode("{#}", $userInfo["account"]);
            $userInfo["is_del"] = $userArr[1] ?? $userInfo["account"];
            $userInfo["device_id"] = $loginfo["device_id"]?? "";
            $this->assign('userInfo', $userInfo);
            $this->assign("statusArr", array(0 => "正常", 1 => '<span class="green">已封号</span>', 2 => '<span class="red">已删除角色</span>'));
            $banModel = new BanModel();
            return $this->fetch();
        }

        $this->error("玩家不存在", url("playerLists"));
    }

    /**
     * 重置玩家帐号
     */
    public function resetUsername()
    {
        $roleId = $this->request->param("role_id");
        if (empty($roleId)) {
            $this->error("参数错误!!!");
        }
        $info = $this->roleModel->find($roleId);
        if (empty($info)) {
            $this->error("角色不存在!!!");
        }
        if ($this->request->isPost()) {
            $username = $this->request->param("username", "", "trim");
            if (empty($username)) {
                $this->error("新帐号不能为空!!!");
            }
            //查询此帐号下有多少个角色
            $num = $this->roleModel->where(array("accname" => $username, "server_id" => $info["server_id"]))->count();
            if ($num > 0) {
                $this->error("此角色帐号下有其他存活的角色，请先删除!!!");
            }
            if (false !== $this->roleModel->where(array("id" => $roleId))->update(array("accname" => $username))) {
                $resArr = PHP2Erlang(BACKGROUP_REFRESH_NEW_SERVER, ['<<"' . $info["accname"] . '">>', '<<"' . $username . '">>']);
                if ($resArr["code"] === 0) {
                    $this->success("重置帐号成功!!!");
                } else {
                    $this->roleModel->where("id", $roleId)->update(["accname" => $info["accname"]]);
                    $this->error($resArr["data"]);
                }
            }
            $this->error("操作数据库失败!!!");
        } else {
            $this->assign("info", $info);
            return $this->fetch();
        }
    }

    /**
     * 删除角色
     */
    public function deleteRole()
    {
        $roleId = $this->request->param("role_id");
        if (empty($roleId)) {
            $this->error("参数错误!!!");
        }
        //查询玩家状态
        $info = $this->roleModel->field("accname,server_id")->find($roleId);
        if (strpos($info["accname"], "{#}deleted")) {
            $this->error("此角色已经是删除状态!!!");
        }
        $res = $this->roleModel->update(array("id" => $roleId, "accname" => $info["accname"] . "{#}deleted"));
        if (false !== $res) {
            $resArr = PHP2Erlang(16, array(1, $roleId, '<<"' . $info["accname"] . '">>'));
            if ($resArr["code"] === 0) {
                $this->success("角色删除成功!!!");
            }
            $this->error($resArr["data"]);
        }
        $this->error("操作数据库失败!!!");
    }

    /**
     * 恢复被删除的角色
     */
    public function resumeRole()
    {
        $roleId = $this->request->param("role_id");
        if (empty($roleId))
            $this->error("参数错误!!!");
        //查询玩家状态
        $info = $this->roleModel->field("accname,server_id")->find($roleId);
        if (!strpos($info["accname"], "{#}deleted")) {
            $this->error("此角色是正常状态!!!");
        }
        list($username, $isDel) = explode("{#}", $info["accname"]);
        //查询此帐号下有多少个角色
        $num = $this->roleModel->where(array("accname" => $username, "server_id" => $info["server_id"]))->count();
        if ($num > 0) {
            $this->error("此角色帐号下有其他存活的角色，请先删除!!!");
        }
        $res = $this->roleModel->update(array("id" => $roleId, "accname" => $username));
        if (false !== $res) {
            $resArr = PHP2Erlang(16, array(0, $roleId, '<<"' . $username . '">>'));
            if ($resArr["code"] === 0) {
                $this->success("角色恢复成功!!!");
            }
            $this->error($resArr["data"]);
        }
        $this->error("操作数据库失败!!!");
    }

    /**
     * 玩家背包物品
     */
    public function showPackInfo()
    {
        // $place = $this->request->param("place", 2, "intval");
        $roleId = $this->request->param("role_id", 0);
        if (!$roleId) {
            $this->error("获取数据失败");
        }
        $info = $this->roleModel->field("name")->find($roleId);
        $res = PHP2Erlang(BACKGROUND_ROLE_BAG, [$roleId]);
        Log::write("debug role data" . json_encode($res));
        if ($res["code"] != 0) {
            $this->error("获取数据失败");
        }
        $data = json_decode($res["data"]);
        $this->assign("roleId", $roleId);
        $this->assign("nickname", $info["name"]);
        $newdata = [];
        foreach ($data as $key => $val) {
            $cf = getItemConfigById($key);

            $newdata[] = ["name" => $cf["name"], "num" => $val, "id" => $cf["id"], "desc" => $cf["desc"]];
        }
        $this->assign("data", $newdata);
        return $this->fetch();

    }

    /**
     * 查看虚拟资产
     */
    public function showEconomyInfo()
    {
        $roleId = $this->request->param("role_id", 0);
        if (!$roleId) {
            $this->error("获取数据失败");
        }
        $info = $this->roleModel->field("name")->find($roleId);
        $res = PHP2Erlang(BACKGROUND_GET_ROLE_INFO, [$roleId]);
        Log::write("debug role data" . json_encode($res));
        if ($res["code"] != 0) {
            $this->error("获取数据失败");
        }
        $data = json_decode($res["data"]);
        $this->assign("roleId", $roleId);
        $this->assign("nickname", $info["name"]);
        $newdata = [];
        foreach ($data as $key => $val) {
            $cf = getAssetsConfigByName($key);

            $newdata[] = ["name" => $cf["name"], "value" => $val, "id" => $cf["id"], "desc" => $cf["desc"]];
        }
        $this->assign("data", $newdata);
        return $this->fetch();
    }

    /**
     * 删除玩家背包或者身上物品
     */
    public function deleteItem()
    {
        $itemId = $this->request->param("id");
        $playerId = $this->request->param("role_id");
        $num = $this->request->param("num");
        if (empty($itemId) || empty($playerId)) {
            $this->error("参数错误");
        }
        $num = -abs($num);

        // $num = (int)Db::table(config("database.game") . ".role_item")->where(array("id" => $itemId, "role_id" => $playerId))->value("num");
        $resArr = PHP2Erlang(BACKGROUP_REDUCE_ASSETS, [$playerId, $itemId, $num]);
        if ($resArr["code"] === 0) {
            $this->success("删除成功");
        } else {
            $this->error($resArr["data"]);
        }
    }

    /**
     * 操作玩家资产
     */
    public function updateEconomy()
    {
        $type = $this->request->param("type", 0, "intval");
        $field = $this->request->param("field", 1, "intval");
        $roleId = $this->request->param("role_id", 0);
        if ($this->request->isPost()) {
            $number = $this->request->param("number", 0, "intval");
            if ($number <= 0) {
                $this->error("请输入正整数!!!");
            }
            if (empty($roleId) || empty($field)) {
                $this->error("提交参数错误!!!");
            }
            //扣除操作
            if ($type == 1) {
                //查询当前玩家资产剩余数
                $economyConf = getDiffConfig("data_economy");
                $residue = Db::table(config("database.game") . ".role_economy")->where(array("role_id" => $roleId))->value($economyConf[$field]["field"]);
                if ($residue < $number) {
                    $this->error($economyConf[$field]["name"] . "剩余{$residue},不足以扣除!!!");
                }
            }
            //提交给后端处理
            $resArr = PHP2Erlang(3, array($roleId, $field, $type, $number));
            if ($resArr["code"] === 0) {
                $this->success("操作成功，延迟回写，请上号确认!!!");
            }
            $this->error("操作失败:" . $resArr["data"]);
        } else {
            $this->assign("roleId", $roleId);
            $this->assign("type", $type);
            $this->assign("field", $field);
            return $this->fetch();
        }
    }

    /**
     * 查看玩家拥有武将
     * @adminMenu(
     *     'name' => '查看玩家拥有武将',
     *     'parent' => 'index',
     *     'display' => false,
     *     'hasView' => true,
     *     'order' => 10000,
     *     'icon' => '',
     *     'remark' => '查看玩家拥有武将',
     *     'param' => ''
     * )
     * @return mixed
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function showHeroInfo()
    {
        $roleId = $this->request->param("role_id");
        $data = PHP2Erlang(BACKGROUND_QUERY_PLAYER_HERO_LIST, [$roleId]);
        if ($data["code"] != 0) {
            $this->error("获取数据失败");
        }
        // Log::write("debug hero data" . json_encode($data));
        $hero_data = json_decode($data["data"], true);
        if (!empty($hero_data)) {
            ksort($hero_data);
        }
        $newHerodata = [];
        if (!empty($hero_data))
            foreach ($hero_data as $id => $value) {
                $cf = getHeroConfig($value["base_id"]);
                $value["name"] = $cf["name"];
                $value["quality"] = $cf["quality"];
                $value["is_core"] = $cf["is_core"];
                $value["realm"] = $cf["realm"];
                $value["id"] = $id;

                $newHerodata[] = $value;
            }

        usort($newHerodata, function ($a, $b) {
            if (empty($a) || empty($b))
                return 0;
            if ($a['star'] != $b['star']) {
                return $b['star'] - $a['star'];
            }
            if ($a['lev'] != $b['lev']) {
                return $b['lev'] - $a['lev'];
            }
            if ($a['realm'] != $b['realm']) {
                return $a['realm'] - $b['realm'];
            }
            if ($a['quality'] != $b['quality']) {
                return $b['quality'] - $a['quality'];
            }
            return $a['base_id'] - $b['base_id'];
        });


        // $hero_config = getDiffConfig("hero_data");
        $this->assign(array(
            "data" => $newHerodata,
            "nickname" => $this->request->param("name", "", "urldecode"),
            "roleId" => $roleId,
            // "heroConf" => $hero_config
        ));
        // Log::write("debug hero config".json_encode($hero_config));
        return $this->fetch();
    }

    /**
     * 当前玩家在线
     */
    public function currentOnline()
    {
        $dayOnlineModel = new DayOnlineModel();
        //总注册玩家
        $info["player_total"] = $this->roleModel->count();
        //总登陆人数
        $info["login_total"] = $this->roleModel->where("last_login_time > 0")->count();
        //当前在线情况
        $ipNumSql = $this->roleModel->field('COUNT(*) as total, COUNT(distinct last_login_ip) as ip_num')->where(array('is_online' => 1))->find();
        //当前所有在线
        $info["all_online_num"] = $ipNumSql['total'];
        //当前IP在线
        $info["ip_num_total"] = $ipNumSql['ip_num'];
        //查询当天的在线信息
        $result = $dayOnlineModel::field('online_txt')->where(array('day' => date('Ymd', strtotime('-1 days')), "stat_project" => 1, "type" => 0))->select();
        $minute = getTimeArr(300, false);
        $yesterdayOnline = 0;
        //所有平台的在线，所以要累加
        foreach ($result as $rs) {
            $yesterdayOnlineArr = unserialize($rs['online_txt'], ["classes_allowed" => true]);
            if (isset($yesterdayOnlineArr[$minute])) {
                $yesterdayOnline += $yesterdayOnlineArr[$minute];
            }
        }
        //排序
        $orderStr = $this->request->param('order', 'desc_lev', 'trim');
        list($sort, $field) = explode('_', $orderStr, 2);
        $onlines = $this->roleModel->where(array('is_online' => '1'))->order("{$field} {$sort}")->paginate($this->request->param("pagesize", 20));
        $this->assign("page", $onlines->render())
            ->assign("arr", $sort)
            ->assign("order", $field)
            ->assign("onlineInfo", $onlines)
            ->assign("yesterdayOL", $yesterdayOnline)
            ->assign("info", $info);
        return $this->fetch();
    }

    /**
     * 已封账号列表
     */
    public function blockUserList()
    {

        $data = Db::table("log_ban")
            ->paginate($this->request->param("pagesize", 20));
        $data->appends($this->request->param());
        $page = $data->render();
        $this->assign([
            "data" => $data,
            "page" => $page
        ]);
        return $this->fetch();
    }

    /**
     * 已封IP记录
     */
    public function blockIpList()
    {
        $where["type"] = 1;
        $ip = $this->request->param("ip", "", "trim");
        if (!empty($ip)) {
            $where["value"] = $ip;
        }
        $model = new BanModel();
        $data = $model::where($where)->paginate(20);
        $data->appends($this->request->param());
        $this->assign("data", $data);
        $this->assign("page", $data->render());
        return $this->fetch();
    }

    /**
     * 游戏邮件列表
     * @param RoleMailModel $mailModel
     * @return mixed
     */
    public function roleMail(RoleMailModel $mailModel)
    {
        $timeField = "ctime";
        $sDay = $this->request->param("sDay", date("Y-m-d"));
        $eDay = $this->request->param("eDay", date("Y-m-d"));
        $data = $mailModel->alias("a")
            ->whereBetween($timeField, [strtotime($sDay . " 00:00:00"), strtotime($eDay . " 23:59:59")])
            ->where(function (Query $query) {
                $roleId = $this->request->param("role_id", 0, "trim");
                if ($roleId) {
                    $query->where("rec_role_id", $roleId);
                }
                $itemCode = $this->request->param("item_code", 0, "trim");
                if ($itemCode) {
                    $query->where("attach", "REGEXP", "$itemCode,[0-9]");
                }
            })
            ->leftJoin([config("database.game") . ".role" => "b"], "b.id = a.send_role_id")
            ->leftJoin([config("database.game") . ".role" => "c"], "c.id = a.rec_role_id")
            ->field("a.*,b.name AS from_name,c.name AS to_name")
            ->order("$timeField  DESC")->paginate($this->request->param("pagesize", 20));
        Log::write("mail model laste query sql" . $mailModel->getLastSql());
        $data->appends($this->request->param());
        $this->assign("data", $data);
        $this->assign("page", $data->render());
        $this->assign("itemConf", getDiffConfig("item"));
        return $this->fetch();
    }

    /**
     * 后台发送邮件管理
     * @param MailModel $model
     * @return mixed
     * @throws DbException
     * @throws \think\exception\DbException
     */
    public function sysMail(MailModel $model)
    {
        $title = $this->request->param("title", "", "trim");
        $content = $this->request->param("content", "", "trim");
        $map = [];
        if ($title) {
            $map["title"] = ["like", "%$title%"];
        }
        if ($content) {
            $map["content"] = ["like", "%$content%"];
        }
        $data = $model->where(new Where($map))->order("status ASC,id DESC")->paginate(self::$pageSize);
        Log::write("debug mail data" . json_encode($data, true));
        $data->appends($this->request->param());
        $this->assign("data", $model->getList($data));
        $this->assign("page", $data->render());
        return $this->fetch();
    }

    /**
     * 删除邮件
     * @param MailModel $model
     * @throws \Exception
     */
    public function deleteSysMail(MailModel $model)
    {
        $ids = $this->request->param("ids", 0);
        if (empty($ids)) {
            $this->error("请选择要删除的对象");
        }
        if (false !== $model->whereIn("id", explode(",", $ids))->delete()) {
            $this->success("删除成功");
        }
        $this->error("删除失败");
    }

    public function loginGame()
    {
        $username = $this->request->param("accname", "", "trim");
        $server = Cache::store("file")->get("server_info");
        if (empty($username)) {
            $roleId = $this->request->param("role_id");
            $roleModel = new RoleModel();
            $info = $roleModel::where("id", $roleId)->find();
        } else {
            $info = [
                'pf' => $server['platform'],
                // 'accname' => $username,
                'zone_id' => $server['plat_server'],
                'account' => $username,
            ];
        }
        if (empty($info)) {
            $this->error("玩家信息为空!!!");
        }
        //        $varModel = new VarModel();
        $nowtime = time();
        $passstr = $info["account"] . $nowtime . config("secure.SERVER_SECURE_KEY");
        Log::write("pass str" . $passstr);
        $sign = md5($passstr);
        $params = [
            "ret" => 1,
            "time" => $nowtime,
            "account" => $info["account"],
            "platform" => $info["pf"],
            "zone_id" => $info["zone_id"],
            "is_https" => $server["is_https"] ?? 0,
            "sign" => $sign,
            "login" => base64_encode(string2ascii($server["socket"] . ":" . $server["port"] . ":" . $server["socket"], false))
        ];
        $houtai = "/index_admin.html?";


        $cdnUrl = $server["cdn_url"];
        $is_https = (int) ($server["is_https"] ?? 0);
        //默认不开启https的时候走http cdn
        if ($is_https == 0) {
            $cdnUrl = str_replace('https', 'http', $cdnUrl);
        }

        $url = $cdnUrl . $houtai . urldecode(http_build_query($params));
        //        Header("Location: $url");
        //    Log::write("cdn_url" . $server["cdn_url"] . "redirect_url:=>" . $url);
        $this->redirect($url);
    }
}